package de.karlNet.login;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.stereotype.Controller;

import de.karlNet.Enums.BinaryMaskEnumMapper;
import de.karlNet.login.attributeMapper.ObjectExtractor;
import de.karlNet.sambamanager.ldapModel.LdapObject;

@Controller
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class AttributeObjectMapper implements AttributesMapper {
	private BinaryMaskEnumMapper<Useraccountcontrol> mapper = new BinaryMaskEnumMapper<Useraccountcontrol>(
			Useraccountcontrol.class);

	@Autowired
	private ObjectExtractor objectExtractor;

	protected Set<Useraccountcontrol> getUseraccountcontrol(
			final int userAccountValue) {
		return this.mapper.getEnums(userAccountValue);
	}

	private List<String> getMemberList(Attributes attributes)
			throws NamingException {
		ArrayList<String> memberList = new ArrayList<String>();
		if (attributes.get("member") != null) {
			NamingEnumeration<?> memberEnum = attributes.get("member").getAll();
			while (memberEnum.hasMore()) {
				String memberDN = (String) memberEnum.next();
				memberList.add(memberDN);
			}
		}
		return memberList;
	}

	private List<String> getMemberOfList(Attributes attributes)
			throws NamingException {
		ArrayList<String> memberList = new ArrayList<String>();
		if (attributes.get("memberof") != null) {
			NamingEnumeration<?> memberEnum = attributes.get("memberof")
					.getAll();
			while (memberEnum.hasMore()) {
				String memberDN = (String) memberEnum.next();
				memberList.add(memberDN);
			}
		}
		return memberList;
	}

	@Override
	public Object mapFromAttributes(Attributes attributes)
			throws NamingException {
		LdapObject objectToReturn = null;

		List<String> objectClasses = new ArrayList<String>();

		NamingEnumeration<?> objectclassEnum = attributes.get("objectclass")
				.getAll();
		while (objectclassEnum.hasMore()) {
			String objectClass = (String) objectclassEnum.next();
			objectClasses.add(objectClass);
		}
		objectToReturn = objectExtractor.extract(attributes, objectClasses);
		String orignaldn = null;
		if (attributes.get("originaldn") != null) {
			orignaldn = (String) attributes.get("originaldn").get();
			objectToReturn.setOriginalDN(orignaldn);
		}

		objectToReturn.getMembers().addAll(this.getMemberList(attributes));
		objectToReturn.getMemberOf().addAll(this.getMemberOfList(attributes));
		return objectToReturn;
	}
}
